package com.kcsj.controller.authority;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kcsj.domain.user.Customer;
import com.kcsj.domain.user.User;
import com.kcsj.service.user.CustomerService;
import com.kcsj.util.JSONUtil;
import com.kcsj.util.MessageHelper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
/**
 * @author 傅立贤
 * 25th Nov. 2020
 */
@Slf4j
@WebServlet("/register.ctl")
public class RegisterController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //根据request对象，获得代表参数的JSON字串
        String req_json = JSONUtil.getJSON(request);
        try {
            JSONObject jsonObject = JSONObject.parseObject(req_json);
            Customer customer = jsonObject.getObject("actor", Customer.class);
            User user = JSON.parseObject(req_json,User.class);
            user.setActor(customer);
            CustomerService.getInstance().register(user);
            JSONObject message =
                    MessageHelper.addMessage
                            ("恭喜，注册成功!请登录您的注册邮箱进行激活您的账号，激活后才能登录。");
            response.getWriter().print(message);
        }catch (SQLException e){
            e.printStackTrace();
            log.error(e.getMessage());
            JSONObject message = MessageHelper.dateBaseError();
            response.getWriter().println(message);
        }catch(Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            JSONObject message = MessageHelper.netWordError();
            response.getWriter().println(message);
        }
    }
}